# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix) {
  substring(str, 1, nchar(prefix)) == prefix
}

library(optparse)
library(ropls)
library(magrittr)
library(ggrepel)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value")

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

uniqueClassNote <- unique(sampleInfo$ClassNote)
for (i in 1:length(uniqueClassNote)) {
  classNote <- uniqueClassNote[i]
  eachData <- data %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    filter(ClassNote == classNote) %>%
    column_to_rownames("SampleID")

  x <- eachData %>%
    select(-c("ClassNote")) %>%
    as.matrix()

  tbf <- eachData

  # print("=tbf=")
  # print(tbf)

  crossValI <- min(nrow(x), 7)
  # print(crossValI)

  b <- F

  while (!b) {
    tryCatch({
               pcaRs <- opls(x, plotL = F, crossvalI = crossValI)
               b <- T
             }, error = function(e) {
      x <<- x * 10
      b <<- F
    })
  }

  pcaRs <- opls(x, plotL = F, crossvalI = crossValI)

  print("===")
  print(pcaRs@modelDF)

  df <- pcaRs@modelDF %>%
    as_tibble()
  if (nrow(df) < 2) {
    pcaRs <- opls(x, plotL = F, crossvalI = crossValI, predI = 2)
  }

  parameterData <- pcaRs@modelDF %>%
    select(c(1:2)) %>%
    set_colnames(c("R2", "Cumulative R2")) %>%
    mutate(pcName = paste0("PC", 1:n())) %>%
    as_tibble() %>%
    column_to_rownames("pcName") %>%
    t()
  print(parameterData)
  write.csv(parameterData, paste0(classNote, "_PCA_R2.csv"), quote = FALSE)

  pcData <- pcaRs@scoreMN %>%
    as.data.frame() %>%
    rownames_to_column("SampleID") %>%
    select("SampleID", num_range("p", 1:5)) %>%
    rename_at(vars(-c("SampleID")), function(x) {
      str_replace(x, "p", "PC")
    }) %>%
    column_to_rownames("SampleID")

  write.csv(pcData, paste0(classNote, "_PCA_Score.csv"), quote = FALSE)
}




